package org.rcloud.io.controller;

import com.alibaba.fastjson.JSONObject;
import org.rcloud.io.Utils.ResultVo;
import org.rcloud.io.model.Likes;
import org.rcloud.io.service.LikesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

/**
 * Created by Administrator on 2019/4/3.
 */
@RestController
@RequestMapping(value = "/Likes")
public class LikesController {
    @Autowired
    private LikesService likesService;

    /*
    * 点赞
    *
    * */
    @RequestMapping(value = "/add",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @CrossOrigin
    public int add(@RequestBody String params){
        Likes likes = JSONObject.parseObject(params.toString(),Likes.class);
        Likes likes1 = (Likes) likesService.selectByPrimaryKey(likes).getInfo();
        if (null!=likes1){
            Likes likes2 = new Likes();
            if (likes1.getFlag().equals(1)) {//带引号报错，因为likes1.getFlag()是 Integer类型
                likes2.setArticleid(likes1.getArticleid());
                likes2.setFlag(0);
                likes2.setCreatetime(new Date());
                if (Integer.valueOf(likesService.updateByPrimaryKeySelective(likes2).getInfo().toString())==1){
                    return 2;
                }
            }else {
                likes2.setArticleid(likes1.getArticleid());
                likes2.setFlag(1);
                likes2.setCreatetime(new Date());
                if (Integer.valueOf(likesService.updateByPrimaryKeySelective(likes2).getInfo().toString()) ==1){
                    return 3;
                }
            }
            return Integer.valueOf(likesService.updateByPrimaryKeySelective(likes2).getInfo().toString());
        }else {
            JSONObject object = JSONObject.parseObject(params);
            object.put("id", UUID.randomUUID());
            object.put("createtime",new Date());
            object.put("flag",1);
            Likes likes3 = JSONObject.parseObject(object.toString(),Likes.class);
            return Integer.valueOf(likesService.insertSelective(likes3).getInfo().toString());
        }
    }

    @RequestMapping("/selectbyuserid")
    @ResponseBody
    @CrossOrigin
    public ResultVo selectByUserId(@RequestBody String params) {
        JSONObject object = JSONObject.parseObject(params);
        String userId = (String) object.get("userId");
        return likesService.selectByUserId(userId);
    }

}
